package com.aaa.order.service.impl;

import com.aaa.entity.AccountOrder;
import com.aaa.entity.Order;
import com.aaa.order.dao.OrderDao;
import com.aaa.order.feign.CarFeign;
import com.aaa.order.feign.MemberFeign;
import com.aaa.order.service.OrderService;
import com.aaa.util.HttpClient;
import com.aaa.vo.AccountOrderVo;
import com.aaa.vo.Result;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author 崔灿
 * @Date 2023/03/03 09:30
 * @ClassName OrderService
 * @Description
 * @Version 1.0
 */

@Service
public class OrderServiceImpl implements OrderService {

    @Value("${weixin.appid}")
    private String appid;
    @Value("${weixin.mch_id}")
    private String mchid;
    @Value("${weixin.api_key}")
    private String apiKey;

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private CarFeign carFeign;

    @Autowired
    private MemberFeign memberFeign;

    @Override
    public Result selectAll(Integer currentPage, Integer pageSize, Order order) {
        PageHelper.startPage(currentPage,pageSize);
        List<Order> orders = orderDao.selectAll(order);
        PageInfo<Order> orderPageInfo = new PageInfo<>(orders);
        return new Result(2000,"成功",orderPageInfo);
    }

    @Override
    public Result update(Order order) {
        int i = orderDao.updateById(order);
        return new Result(2000,"成功",order);
    }

    @Override
    public Result selectByMemberId( Integer memberId,Integer state) {
        List<Order> orders = orderDao.selectByMemberId(memberId,state);
        return new Result(2000,"成功",orders);
    }

    @Override
    public Result findByMemberId(AccountOrderVo accountOrderVo) {
        List<AccountOrder> accountOrders = orderDao.findByMemberId(accountOrderVo);
        return new Result(2000,"成功",accountOrders);
    }

    @Override
    @Transactional
    public Result insert(Order order) {
        if (order.getPayStyle()==0){
            order.setState(4);
        }
        order.setAddtime(new Date());
        orderDao.insert(order);
        //根据memberID查询member，减余额
        Integer memberId = order.getMemberId();
        Double accountBalance = order.getPreparidAmount();
        memberFeign.updateAmount(memberId, accountBalance);

        //修改汽车的状态
        Integer carId = order.getCarId();
        System.out.println("carId = " + carId);
        carFeign.updateState(carId);

        //修改优惠券的状态
        Integer couponId = order.getCouponId();
        if (couponId!=1){
            Date date = new Date();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = simpleDateFormat.format(date);
            memberFeign.updateState(couponId,format);
        }

        return new Result(2000,"成功",order);
    }

    @Override
    public Result createNative(Order order) {
        //先创建一个支付订单
        order.setState(1);
        order.setAddtime(new Date());
        orderDao.insert(order);
        //获取创建订单的id
        Integer id = order.getId();
        //1.订单号查询订单信息
        QueryWrapper<Order> wrapper=new QueryWrapper<>();
        wrapper.eq("id",id);
        wrapper.eq("state",1);
        Order order1 = orderDao.selectOne(wrapper);
        if(order1!=null){

            //请求参数的封装
            Map<String,String> params=new HashMap<>();
            params.put("appid",appid);
            params.put("mch_id",mchid);
            params.put("nonce_str", WXPayUtil.generateNonceStr());
            params.put("out_trade_no",id.toString());
            params.put("body","WeChatPay");
            params.put("total_fee",new BigDecimal(0.01).multiply(new BigDecimal(100)).longValue()+"");
            params.put("spbill_create_ip","127.0.0.1");//真实服务器的ip
            params.put("notify_url","http://localhost:8080/pay/back");//支付成功后跳转的路径
            params.put("trade_type","NATIVE");
            try {
                //2.远程调用微信支付接口
                HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
                //设置支持https协议的请求
                httpClient.setHttps(true);
                //设置xml格式的参数
                httpClient.setXmlParam(WXPayUtil.generateSignedXml(params, apiKey));
                //发送请求
                httpClient.post();

                //获取返回的结果
                String content = httpClient.getContent();
                //把xml转化为map
                Map<String, String> map = WXPayUtil.xmlToMap(content);
                System.out.println("map = " + map);
                if(map.get("result_code").equals("SUCCESS")){
                    Map<String,Object> result=new HashMap<>();
                    result.put("code_url",map.get("code_url"));
                    result.put("id",order1.getId());
                    result.put("preparidAmount",order1.getPreparidAmount());
                    return new Result(2000,"获取二维码地址成功",result);
                }
            }catch (Exception e){
                e.printStackTrace();
            }

        }

        return new Result(5000,"订单失效",null);

    }

    @Override
    public Result queryOrderStatus(Integer id) {
        Map<String,String> params=new HashMap<>();
        params.put("appid",appid);
        params.put("mch_id",mchid);
        params.put("out_trade_no",id.toString());
        params.put("nonce_str", WXPayUtil.generateNonceStr());
        try {
            HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            httpClient.setHttps(true);
            httpClient.setXmlParam(WXPayUtil.generateSignedXml(params, apiKey));

            httpClient.post();
            String content = httpClient.getContent();

            Map<String, String> map = WXPayUtil.xmlToMap(content);
            if(map.get("trade_state").equals("SUCCESS")){
                //1.修改订单状态
                Order order = new Order();
                order.setState(4);
                QueryWrapper<Order> wrapper=new QueryWrapper<>();
                wrapper.eq("id",id);
                wrapper.eq("state",1);
                orderDao.update(order,wrapper);
                return new Result(2000,"支付成功",null);
            }

        }catch (Exception e){
            e.printStackTrace();
        }

        return new Result(5000,"支付失败",null);
    }

    @Override
    public Result updateAllState(Order order) {
        //根据memberID查询member，减余额
        Integer memberId = order.getMemberId();
        Double accountBalance = order.getPreparidAmount();
        memberFeign.updateAmount(memberId, accountBalance);

        //修改汽车的状态
        Integer carId = order.getCarId();
        System.out.println("carId = " + carId);
        carFeign.updateState(carId);

        //修改优惠券的状态
        Integer couponId = order.getCouponId();
        if (couponId!=-1){
            Date date = new Date();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = simpleDateFormat.format(date);
            memberFeign.updateState(couponId,format);
        }


        return new Result(2000,"成功",order);
    }

    @Override
    public Result createMQ(Integer id) {
        String s1 = id.toString();
        //确保消息传到交换机
//        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
//            @Override
//            public void confirm(CorrelationData correlationData, boolean b, String s) {
//                if (b==false){
//                    //弥补机制--重新发送--取消订单--业务
//                    rabbitTemplate.convertAndSend("order_exchange","",s1);
//
//                }
//            }
//        });
        rabbitTemplate.convertAndSend("order_exchange","",""+s1);
        return new Result(2000,"成功",null);
    }
}

